package cli

import (
	"gamesdk/common/libnet/inter"
	"gamesdk/common/libnet/msg"
	"gamesdk/common/log"
	"sync"
	"time"

	"github.com/clock"
	"github.com/golang/protobuf/proto"
)

/*
*用户缓存
 */
type AIClient struct {
	readBuf    chan []byte
	readClose  chan bool
	reciveMsg  inter.ReciveMsg
	exit       bool
	waitGroup  sync.WaitGroup
	ai_manager inter.InterAIManager
}

func NewAIClient(manager inter.InterAIManager) *AIClient {
	return &AIClient{
		reciveMsg:  nil,
		readBuf:    make(chan []byte, 1024),
		readClose:  make(chan bool),
		exit:       false,
		ai_manager: manager,
	}
}

/*
*初始化服务
*参数说明:
*@param:reciveMsg   	接受消息回调函数
 */
func (this *AIClient) Start(reciveMsg inter.ReciveMsg, exit inter.Exit) {
	this.reciveMsg = reciveMsg
	for {
		select {
		case buf := <-this.readBuf:
			frameMsg := &msg.FrameMsg{}
			err := proto.Unmarshal(buf, frameMsg)
			if err != nil {
				log.Warn(err.Error())
				break
			}
			//表示心跳包
			if frameMsg.MainCmd == 0 {
				log.Debug("recvice heart data")
				break
			}
			if this.reciveMsg != nil {
				//log.Debug("reciveMsg")
				this.reciveMsg(frameMsg.MainCmd, frameMsg.SubCmd, frameMsg.Buff)
			}
		case <-this.readClose:
			goto A
			//ticker.Stop()
			//return
		}
	}
A:

	//关闭资源
	this.waitGroup.Wait()
	close(this.readClose)
	close(this.readBuf)
	this.exit = true
	exit()
	return
}

/*
*发生消息 send_msg_to_user
 */
func (this *AIClient) SendMsgToClinet(message []byte) {

	if !this.exit {
		go this.ai_manager.OnSendMsgToClient(this, message)
	}
}

func (this *AIClient) SendMsgToServer(message []byte) {
	if !this.exit {
		this.readBuf <- message
	}
}

//添加定时器
func (this *AIClient) AddTimer(actionInterval time.Duration, jobFunc func()) (job clock.Job, ok bool) {
	return this.ai_manager.AddTimer(actionInterval, jobFunc)
}

//添加定时器
func (this *AIClient) AddTimerRepeat(interval time.Duration, actionMax uint64, jobFunc func()) (jobScheduled clock.Job, inserted bool) {
	return this.ai_manager.AddTimerRepeat(interval, actionMax, jobFunc)
}

/*
*用户推出
 */
func (this *AIClient) Exit() {
	this.readClose <- true
}

func (this *AIClient) GetIp() string {
	return "127.0.0.1"
}
